/*
 *  Copyright (c) 1998, Regents of the University of California
 *  All rights reserved.
 *  Redistribution and use in source and binary forms, with or without
 *  modification, are permitted provided that the following conditions are met:
 *
 *      * Redistributions of source code must retain the above copyright
 *        notice, this list of conditions and the following disclaimer.
 *      * Redistributions in binary form must reproduce the above copyright
 *        notice, this list of conditions and the following disclaimer in the
 *        documentation and/or other materials provided with the distribution.
 *      * Neither the name of the University of California, Berkeley nor the
 *        names of its contributors may be used to endorse or promote products
 *        derived from this software without specific prior written permission.
 *
 *  THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND ANY
 *  EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 *  WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 *  DISCLAIMED. IN NO EVENT SHALL THE REGENTS AND CONTRIBUTORS BE LIABLE FOR ANY
 *  DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 *  (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 *  LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 *  ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 *  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 *  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
package org.demis.wizard;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.velocity.Template;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;
import org.apache.velocity.exception.MethodInvocationException;
import org.apache.velocity.exception.ParseErrorException;
import org.apache.velocity.exception.ResourceNotFoundException;
import org.demis.elf.Schema;
import org.demis.elf.Table;
import org.demis.elf.configuration.SupportedDBMS;
import org.demis.elf.dbreader.SchemaReader;
import org.demis.elf.dbreader.postgresql.PostgresqlSchemaReader;
import org.demis.orc.DataBaseToObjectConverter;
import org.demis.orc.Mapping;
import org.demis.orc.NameHelper;
import org.demis.troll.ClassDescriptor;
import org.demis.troll.ObjectModelHelper;
import org.demis.troll.PackageDescriptor;

/**
 * @version 1.0
 * @author <a href="mailto:demis27@demis27.net">Stéphane kermabon</a>
 */
public class WizardGenerator {

    private static final Log logger = LogFactory.getLog(WizardGenerator.class);

    private WizardConfiguration configuration;

    private NameHelper nameHelper = new NameHelper();

    public WizardGenerator(WizardConfiguration configuration) {
        this.configuration = configuration;
    }

    public void generate() {
        Schema schema = readSchema(configuration.getDatabaseConfiguration());
        List<ClassDescriptor> classes = generateObjectModel(configuration, schema);

        VelocityContext context = new VelocityContext();
        context.put("mapping", Mapping.getInstance());
        context.put("nameHelper", nameHelper);
        context.put("objectModelHelper", ObjectModelHelper.getInstance());
        context.put("databaseConfiguration", configuration.getDatabaseConfiguration());
        context.put("objectConfiguration", configuration.getObjectConfiguration());

        for (TemplateConfiguration templateConfiguration: configuration.getFilesConfiguration()) {
            Template velocityTemplate = initVelocity(templateConfiguration.getTemplateName(), configuration.getTemplatesPath());

            context.put("templateConfiguration", templateConfiguration);

            if (templateConfiguration.getTarget().equals("table")) {
                for (ClassDescriptor classDescriptor: classes) {
                    context.put("classDescriptor", classDescriptor);
                    generateFile(velocityTemplate, context);
                }
            }
            else if (templateConfiguration.getTarget().equals("schema")) {
                context.put("schema", schema);
                generateFile(velocityTemplate, context);
            }
            
        }

    }

    private void generateFile(Template velocityTemplate, VelocityContext context) {
        try {
            FileOutputStream fileOutput = null;
            StringWriter writer = new StringWriter();
            velocityTemplate.merge(context, writer);
            String path = ((TemplateConfiguration)(context.get("templateConfiguration"))).getPath();
            String filename = path + File.separator + ((TemplateConfiguration)(context.get("templateConfiguration"))).getFileNameTemplate();

            if ((ClassDescriptor)context.get("classDescriptor") != null) {
                filename = parseFileName((ClassDescriptor)context.get("classDescriptor"), filename);
            }

            if (logger.isInfoEnabled()) {
                logger.info("filename : " + filename);
                logger.info("path : " + path);
            }

            File filePath = new File(filename.substring(0, filename.lastIndexOf('/')));
            filePath.mkdirs();
            fileOutput = new FileOutputStream(filename);
            fileOutput.write(writer.toString().getBytes());
            
        } catch (ResourceNotFoundException ex) {
            Logger.getLogger(WizardGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ParseErrorException ex) {
            Logger.getLogger(WizardGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (MethodInvocationException ex) {
            Logger.getLogger(WizardGenerator.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(WizardGenerator.class.getName()).log(Level.SEVERE, null, ex);
        }
    }


    private Schema readSchema(DatabaseConfiguration databaseConfiguration) {
        if (logger.isInfoEnabled()) {
            logger.info("read schema from postgresql 8");
            logger.info("schema   : " + databaseConfiguration.getSchema());
            logger.info("user     : " + databaseConfiguration.getUser());
            logger.info("password : " + databaseConfiguration.getPassword());
            logger.info("url      : " + databaseConfiguration.getUrl());
        }


        org.demis.elf.configuration.DatabaseConfiguration elfConfiguration = new org.demis.elf.configuration.DatabaseConfiguration();
        elfConfiguration.setUrl(databaseConfiguration.getUrl());
        elfConfiguration.setDbms(SupportedDBMS.POSTGRESQL8);
        elfConfiguration.setPassword(databaseConfiguration.getPassword());
        elfConfiguration.setSchemaName(databaseConfiguration.getSchema());
        elfConfiguration.setUser(databaseConfiguration.getUser());

        SchemaReader schemaReader;
        if (databaseConfiguration.getType() == SupportedDBMS.POSTGRESQL8) {
            schemaReader = new PostgresqlSchemaReader();
            return schemaReader.read(elfConfiguration);
        }

        return null;
    }

    private List<ClassDescriptor> generateObjectModel(WizardConfiguration configuration, Schema schema) {
        List<ClassDescriptor> classes = DataBaseToObjectConverter.convertSchema(schema);


        for (ClassDescriptor classDescriptor: classes) {
            Table table = Mapping.getInstance().getTable(classDescriptor);
            PackageDescriptor packageDescriptor = new PackageDescriptor();
            packageDescriptor.setName(configuration.getObjectConfiguration().getPackageName() + "." + nameHelper.getPackageName(classDescriptor));

            classDescriptor.setPackageDescriptor(packageDescriptor);
            Mapping.getInstance().addMapping(table, classDescriptor);
        }

        return classes;
    }

    protected Template initVelocity(String templateName, String templatePath) {
        if (logger.isInfoEnabled()) {
            logger.info("templateName " + templateName);
            logger.info("templatePath " + templatePath);
        }
        VelocityEngine ve = new VelocityEngine();
        try {
            Properties p = new Properties();
            //p.setProperty("file.resource.loader.class", "org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
            if (templatePath != null) {
                p.setProperty("file.resource.loader.path", templatePath);
            }
            ve.init(p);
            Template mappingTemplate = ve.getTemplate(templateName);
            return mappingTemplate;
        } catch (ResourceNotFoundException ex) {
            logger.error("template #" + templatePath + "/" + templateName + " not found", ex);
        } catch (ParseErrorException ex) {
            logger.error("template #" + templatePath + "/" + templateName + " not found", ex);
        } catch (Exception ex) {
            logger.error("template #" + templatePath + "/" + templateName + " not found", ex);
        }
        return null;
    }

    private String parseFileName(ClassDescriptor classDescriptor, String fileNameTemplate) {
        String result = fileNameTemplate;
        if (classDescriptor != null) {
            result = result.replaceAll("\\{className\\}", classDescriptor.getClassName());
//            result = result.replaceAll("\\{objectName\\}", classDescriptor.getObjectName());
            PackageDescriptor packageDescriptor = classDescriptor.getPackageDescriptor();
            if (packageDescriptor != null) {
                result = result.replaceAll("\\{packageName\\}", convertPackageNameToPath(packageDescriptor.getName()));
            }
        }
        result = result.replaceAll("\\{defaultpackageName\\}", convertPackageNameToPath(configuration.getObjectConfiguration().getPackageName()));
        return result;
    }

    private static String convertPackageNameToPath(String pakageName) {
        StringTokenizer tokenizer = new StringTokenizer(pakageName, ".");
        StringBuffer buffer = new StringBuffer("");
        while (tokenizer.hasMoreTokens()) {
            buffer.append(File.separator);
            buffer.append(tokenizer.nextToken());
        }
        return buffer.toString();
    }
}
